﻿using GameGravity.PolyNetwork;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

#region 服务器示例
void SetupServer()
{
    var server = new PolyNetwork { Logger = Console.WriteLine, Name = "Server" }
        .Listen("127.0.0.1", 2333)
        .AddListener(msg => new { text = $"hi." });

    if (!Directory.Exists("error"))
    {
        Directory.CreateDirectory("error");
    }

    server.OnError += error =>
    {
        File.WriteAllText($"error/{GetFileDateText()}.txt", error.Message);
        SetupServer();
    };

    string GetFileDateText() => DateTime.Now.ToString("yyyy-MM-dd-H-m-ss");
}

// 入口
SetupServer(); //启动服务器
#endregion


#region 客户端示例

async Task<PolyNetwork> ConnectAsync()
{
    var client = new PolyNetwork { Logger = Console.WriteLine, Name = "Client" };

    ConnectResult connectReport;
    do
    {
        connectReport = await client.Connect("127.0.0.1", 2333);
    } while (connectReport == ConnectResult.error);

    return client;
}

async Task SendAsync(PolyNetwork client)
{
    Console.WriteLine("======== 客户端发送消息：hello ========");

    dynamic serverReport;
    while (true)
    {
        serverReport = await client.Send(new { text = "hello" });
        
        if (serverReport == null && !client.IsConnect)
        {
            client = await ConnectAsync();
        }
        else
        {
            break;
        }
    }

    Console.WriteLine($"======== 服务端返回消息：{serverReport.text} ========");
}

//入口
var client = await ConnectAsync();
await SendAsync(client);
#endregion